﻿using System;
using Kugar.Core.ExtMethod;
using Kugar.UI.Web.AdminLTE.Authentications;
using Kugar.UI.Web.AdminLTE.PageControls;
using Kugar.UI.Web.AdminLTE.PageControls.PageCommon;
using Kugar.UI.Web.AdminLTE.PageControls.PageForms;
using Kugar.UI.Web.AdminLTE.PageControls.SystemComponent;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using HttpContext = Kugar.Core.Web.HttpContext;

namespace Kugar.UI.Web.AdminLTE
{
    public class AdminLTEUI : IViewContextAware
    {
        private static ResourceFileMD5 _resourceFileMd5 = new ResourceFileMD5();

        private static readonly LayoutPath _pather=new LayoutPath();
        private static readonly AdminUrlPath _defaultUrl=new AdminUrlPath();
        
        private Lazy<PageCommonControl> _ctrl = null;
        private Lazy<SystemComponent> _sys = null;
        private int _nextControlIndex = 0;
        private IHtmlHelper _htmlhelper = null;
        private static string _version = "";
        private string _logoutUrl = "";
        

        static AdminLTEUI()
        {
            _version = typeof(AdminLTEUI).Assembly.GetName().Version.ToString(3);
        }

        public AdminLTEUI(IHtmlHelper htmlHelper)
        {
            _htmlhelper = htmlHelper;
            _ctrl=new Lazy<PageCommonControl>(createControl);
            _sys= new Lazy<SystemComponent>(createSys);

            this.LogoutUrl = AdminLTEUI.DefaultAdminUrls.LogoutUrl;

            
        }

        public AdminJWTOption Option { get; private set; }

        /// <summary>
        /// AdmninUI组件相关的一些路径
        /// </summary>
        public static LayoutPath LayoutPath => _pather;

        public static AdminUrlPath DefaultAdminUrls => _defaultUrl;

        public PageCommonControl Control => _ctrl.Value;

        public SystemComponent SystemComponent=> _sys.Value;

        public string DefaultIndexWhenIFrame
        {
            get => (string)ViewContext.ViewBag.DefaultIndexWhenIFrame;
            set => ViewContext.ViewBag.DefaultIndexWhenIFrame = value;
        }

        public static ResourceFileMD5 InternalFileMD5 { 
            get=> _resourceFileMd5;
            set { _resourceFileMd5 = value; }
    }

        public string Version => _version;

        /// <summary>
        /// 当前菜单的key值
        /// </summary>
        public string CurrentMenuKey { set; get; }

        /// <summary>
        /// 在iframe模式下,当前页面在tab上显示的标题,默认等于Title
        /// </summary>
        public string TabPageTitle {
            get => (string)ViewContext.ViewBag.TabPageTitle;
            set => ViewContext.ViewBag.TabPageTitle = value;
        }

        /// <summary>
        /// 当前页面的标题
        /// </summary>
        public string Title
        {
            get => (string)ViewContext.ViewBag.Title;
            set => ViewContext.ViewBag.Title = value;
        }

        /// <summary>
        /// 当前页面的子标题
        /// </summary>
        public string Subtitle
        {
            get => (string)ViewContext.ViewBag.Subtitle;
            set => ViewContext.ViewBag.Subtitle = value;
        }

        /// <summary>
        /// 设置退出用户的Url,默认为当前的logout
        /// </summary>
        public string LogoutUrl
        {
            set => _logoutUrl = value.ToStringEx();
            get => _logoutUrl;
        }

        /// <summary>
        /// 左上角的图片
        /// </summary>
        public string AvatarImageUrl
        {
            set { ViewContext.ViewBag.AvatarSrc = value.ToStringEx(); }
            get { return (string)ViewContext.ViewBag.AvatarSrc; }
        }

        /// <summary>
        /// 左上角,用户信息框,点击后跳转的地址
        /// </summary>
        public string UserInfoHref
        {
            set { ViewContext.ViewBag.UserInfoHrefUrl = value.ToStringEx(); }
            get { return (string)ViewContext.ViewBag.UserInfoHrefUrl; }
        }

        /// <summary>
        /// 设置用于显示在左上角的当前用户名
        /// </summary>
        public string CurrentUserName
        {
            set { ViewContext.ViewBag.UserName = value.ToStringEx(); }
            get
            {
                var userName = (string) ViewContext.ViewBag.UserName;

                if (string.IsNullOrEmpty(userName))
                {
                    userName = ViewContext.HttpContext.User.FindFirst("UserName")?.Value.ToStringEx();
                }
                return userName;
            }
        }

        /// <summary>
        /// 当前页面的面包屑路径
        /// </summary>
        public BreadcrumbItem[] Breadcrumbs { set; get; } = Array.Empty<BreadcrumbItem>();

        /// <summary>
        /// 生成不重复的控件ID序号,页面内不重复,不建议直接调用
        /// </summary>
        /// <returns></returns>
        public int NextControlIndex()
        {
            return _nextControlIndex++;
        }

        /// <summary>
        /// 当前页面的菜单
        /// </summary>
        public PageMenu[] Menus { set; get; }

        public IHtmlHelper HtmlHelper => _htmlhelper;

        public ViewContext ViewContext => _htmlhelper.ViewContext;

        public static bool JqTableEndabled { set; get; } = false;

        /// <summary>
        /// 是否为多页面版本
        /// </summary>
        public bool IsIFrameVersion { set; get; } = false;

        public PluginUsagedInfo PluginUsaged {  get; }=new PluginUsagedInfo();

        void IViewContextAware.Contextualize(ViewContext viewContext)
        {
            if (_htmlhelper is IViewContextAware)
            {
                ((IViewContextAware)_htmlhelper).Contextualize(viewContext);

                ViewContext.ViewBag.WebUI = this;

                if (Option == null)
                {
                    var authenticationType = viewContext.RouteData.Values.TryGetValue("authenticationType").ToStringEx();

                    var options = (OptionsManager<AdminJWTOption>)viewContext.HttpContext.RequestServices.GetService(typeof(OptionsManager<AdminJWTOption>));

                    var option = options.Get(authenticationType);

                    Option = option;

                    var loc = (IStringLocalizer)viewContext.HttpContext.RequestServices.GetService(typeof(IStringLocalizer));

                    Localizer = loc;
                }
                

                

                if (ViewContext.TempData.ContainsKey("nextControlIndex"))
                {
                    _nextControlIndex = (int) ViewContext.TempData["nextControlIndex"];
                }
                else
                {
                    ViewContext.TempData["nextControlIndex"] = _nextControlIndex;
                }
            }
        }

        public IStringLocalizer Localizer { get; private set; }

        private PageCommonControl createControl()
        {
            return new PageCommonControl(ViewContext);
        }

        private SystemComponent createSys()
        {
            return new SystemComponent(ViewContext);
        }

        internal bool IsInPage
        {
            get
            {
                return (bool)ViewContext.ViewData.TryGetValue("IsInPage", false);
            }
            set { ViewContext.ViewData["IsInPage"] = value; }
        }

        internal bool IsInModal
        {
            get
            {
                return (bool)ViewContext.ViewData.TryGetValue("IsInModal", false);
            }
            set { ViewContext.ViewData["IsInModal"] = value; }
        }



        public class PluginUsagedInfo
        {
            public bool SummerNote { set; get; }

            public bool DataTables { set; get; }

            public bool CityPicker { set; get; }

        }
    }

    public class PageCommonControl
    {
        private ViewContext _viewContext = null;
        private Lazy<EmptyForm> _emptyForm = null;

        internal PageCommonControl(ViewContext viewContext)
        {
            _viewContext = viewContext;

            _emptyForm =new Lazy<EmptyForm>(new EmptyForm(_viewContext));
        }

        /// <summary>
        /// 输出一个数据列表控件,包含了一个Querybox和一个Table控件组合
        /// </summary>
        /// <typeparam name="TData"></typeparam>
        /// <returns></returns>
        public PageCommon_DataList<TData> DataList<TData>()=>new PageCommon_DataList<TData>(_viewContext);

        /// <summary>
        /// 输出一个数据选择器控件,建议配合WebUIJS.DataPicker函数使用
        /// </summary>
        /// <typeparam name="TData"></typeparam>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> DataPicker<TData>()=>new PageCommon_DataPicker<TData>(_viewContext);

        /// <summary>
        /// 输出一个弹出框控件
        /// </summary>
        /// <returns></returns>
        public PageCommon_ModalWindow ModalWindow()=>new PageCommon_ModalWindow(_viewContext);

        /// <summary>
        /// 输出一个box控件,使用using输出内容
        /// </summary>
        /// <returns></returns>
        public PageCommon_PanelBoxContainer PanelBoxContainer()=>new PageCommon_PanelBoxContainer(_viewContext);

        /// <summary>
        /// 输出一个Box,直接输出文本或控件作为Content内容
        /// </summary>
        /// <returns></returns>
        public PageCommon_PanelBox PanelBox()=>new PageCommon_PanelBox(_viewContext);

        /// <summary>
        /// 输出一个div,row
        /// </summary>
        /// <returns></returns>
        public PageCommon_Row Row()=>new PageCommon_Row(_viewContext);

        /// <summary>
        /// 输出一个Tab控件
        /// </summary>
        /// <returns></returns>
        public PageCommon_Tab Tab()=>new PageCommon_Tab(_viewContext);

        /// <summary>
        /// 输出一个表格
        /// </summary>
        /// <typeparam name="TData"></typeparam>
        /// <returns></returns>
        public PageCommon_Table2<TData> Table<TData>()=>new PageCommon_Table2<TData>(_viewContext);

        /// <summary>
        /// 输出一个表单控件
        /// </summary>
        /// <returns></returns>
        public PageForm_Form Form()=>new PageForm_Form(_viewContext);

        /// <summary>
        /// 输出一个查询框
        /// </summary>
        /// <returns></returns>
        public PageCommon_QueryBox QueryBox()=>new PageCommon_QueryBox(_viewContext);

        /// <summary>
        /// 输出一个手风琴控件
        /// </summary>
        /// <returns></returns>
        public PageCommon_Accordion Accordion()=>new PageCommon_Accordion(_viewContext);

        /// <summary>
        /// 输出一个轮播图片的控件
        /// </summary>
        /// <returns></returns>
        public PageCommon_Carousel Carousel()=>new PageCommon_Carousel(_viewContext);

        /// <summary>
        /// 输出一个infobox控件,,参考AdminLte的infobox
        /// </summary>
        /// <returns></returns>
        public PageCommon_InfoBox InfoBox()=>new PageCommon_InfoBox(_viewContext);

        /// <summary>
        /// 输出一个进度条控件
        /// </summary>
        /// <returns></returns>
        public PageCommon_Progress Progress()=>new PageCommon_Progress(_viewContext);

        /// <summary>
        /// 输出Callout控件
        /// </summary>
        /// <returns></returns>
        public PageCommon_Callout Callout()=>new PageCommon_Callout(_viewContext);

        /// <summary>
        /// 输出一个按钮控件
        /// </summary>
        /// <returns></returns>
        public PageCommon_Button Button()=>new PageCommon_Button(_viewContext);

        /// <summary>
        /// 输出一个隐藏域
        /// </summary>
        /// <returns></returns>
        public PageCommon_Hidden Hidden()=>new PageCommon_Hidden(_viewContext);

        /// <summary>
        /// 树形结构
        /// </summary>
        /// <typeparam name="TData"></typeparam>
        /// <returns></returns>
        public PageCommon_Tree Tree()=>new PageCommon_Tree(_viewContext);

        /// <summary>
        /// 空的表单
        /// </summary>
        /// <returns></returns>
        public IPageForm EmptyForm() => _emptyForm.Value;
    }

    public class SystemComponent
    {
        private ViewContext _viewContext = null;

        internal SystemComponent(ViewContext viewContext)
        {
            _viewContext = viewContext;
        }

        public PageCommon_ServerMsg ServerMsg()=>new PageCommon_ServerMsg(_viewContext);
    }

    public class LayoutPath
    {
        internal LayoutPath() { }

        public string DefaultLayoutPath { get; } = "~/Views/AdminLTELayout.cshtml";

        public string ResourceBaseUrl { set; get; } = "/adminltebase";

        public string LayoutWithIFramePath { get; } = "~/Views/AdminLTELayoutWithIFrame.cshtml";

        public string LayoutWithIFramePath_Content { get; } = "~/Views/AdminLTELayoutWithIFrame_Content.cshtml";

        public string LoginViewPath { get; }= "~/views/AdminLTE_Login.cshtml";//"~/Views/Login2.cshtml";
    }

    public class AdminUrlPath
    {
        internal AdminUrlPath()
        {
        }

        /// <summary>
        /// 管理员列表
        /// </summary>
        public string AdminListUrl { get; } = "/AdminCore/AdminLogin/AdminList";

        /// <summary>
        /// 使用iframe内容页的管理员列表
        /// </summary>
        public string AdminListUrl_Iframe { get; } = "/AdminCore/AdminLogin/AdminList?isIFrame=true";

        /// <summary>
        /// 登录链接
        /// </summary>
        public string LoginUrl
        {
            get
            {
                var schecmeName = HttpContext.Current == null
                    ? ""
                    : HttpContext.Current.Items.TryGetValue("SchemeName", "").ToStringEx();


                return $"/AdminCore/Login{(string.IsNullOrEmpty(schecmeName) ? "" : "/" + schecmeName)}";
            }
        }

        /// <summary>
        /// 登出地址链接
        /// </summary>
        public string LogoutUrl
        {
            get
            {
                var schecmeName = HttpContext.Current == null
                    ? ""
                    : HttpContext.Current.Items.TryGetValue("SchemeName", "").ToStringEx();

                return $"/AdminCore/Logout{(string.IsNullOrEmpty(schecmeName)?"":"/" + schecmeName)}";
            }
        }

        /// <summary>
        /// 修改密码的链接
        /// </summary>
        public string ChangePassword => "/AdminCore/AdminLogin/ChangePassword";
    }

    public class BreadcrumbItem
    {
        public BreadcrumbItem(string title, string href)
        {
            Title = title;
            Href = href;
        }
        
        public string Title { set; get; }

        public string Href { set; get; }
    }

    public class ResourceFileMD5{
        public string AdminLTEUICSS_css { set; get; }

        public string AdminLTEUICSS_inner_css { set; get; }

        public string AdminLTEUI_iframe_css { set; get; }

        public string webui_ctrl_all_plugins_css { set; get; }

        public string webui_ctrl_all_plugins_js { set; get; }

        public string WebUIJS_js { set; get; }

        public string WebUIJS_inner_js { set; get; }

        public string WebUIJS_iframe_js { set; get; }
    }
}
